package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.tx.TxAccountMessage;
import cn.tedu.order.tx.TxInfo;
import cn.tedu.order.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/9/26 11:47
 */

@Slf4j
@Service
@RocketMQTransactionListener
public class TxOrderServiceImpl implements OrderService, RocketMQLocalTransactionListener {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private TxMapper txMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private RocketMQTemplate t;


    @Override
    public void create(Order order) {

        String xid = UUID.randomUUID().toString().replace("-", "");
        TxAccountMessage accountMessage = new TxAccountMessage(order.getUserId(), order.getMoney(), xid);
        String json = JsonUtil.to(accountMessage);
        // Spring 封装的通用message对象
        // payload 会自动被转换成  byte[]
        Message<String> message = MessageBuilder.withPayload(json).build();

        // 发送事务消息
        // 如果添加tag, 格式: "orderTopic: TagA"
        t.sendMessageInTransaction("orderTopic", message,order);
    }


    //本地事务，执行订单保存
    //这个方法在事务监听器中调用
    @Transactional
    public void doCreate(Order order) {
        log.info("执行本地事务，保存订单");

        // 从全局唯一id发号器获得id
        Long orderId = Long.valueOf(easyIdClient.nextId("order_business"));
        order.setId(orderId);

        orderMapper.create(order);

        log.info("订单已保存！ 事务日志已保存");
    }

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        RocketMQLocalTransactionState state; // 用来返回
        int status; // 用来存储到数据库

        try {
            Order order = (Order) o;
            doCreate(order);
            state = RocketMQLocalTransactionState.COMMIT;
            status = 0;
        } catch (Exception e) {
            e.printStackTrace();
            state = RocketMQLocalTransactionState.ROLLBACK;
            status = 1;
        }

        // 封装事务状态
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        TxInfo txInfo = new TxInfo(xid, status, System.currentTimeMillis());
        txMapper.insert(txInfo);
        return state;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        TxInfo txInfo = txMapper.selectById(xid);
        if (txInfo == null) {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        switch (txInfo.getStatus()) {
            case 0: return RocketMQLocalTransactionState.COMMIT;
            case 1: return RocketMQLocalTransactionState.ROLLBACK;
            default: return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
